package com.ynny.project07.contrller;

import cn.hutool.core.util.StrUtil;
import com.ynny.carbon.common.R;
import com.ynny.carbon.entity.User;
import com.ynny.carbon.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserService userService;

    private static final String SESSION_USER = "SESSION_USER";


    @GetMapping
    public R login(){

        return R.fail(440 , "请先登录");
    }


    @PostMapping
    public R login(@RequestBody User user , HttpSession session){

        if (StrUtil.isBlank(user.getUsername())
                || StrUtil.isBlank(user.getPassword())
        ){
            return R.fail(400 , "用户名或密码不能为空");
        }

        //userRes 是登录成功后 的用户信息
        User userRes = userService
                .login(user.getUsername() , user.getPassword());

        if (userRes != null){
            // 登录成功  保存用户信息到 session作用域 中

            session.setAttribute(SESSION_USER , user.getUsername());

            userRes.setPassword("想知道我的密码？");
            // 返回登录成功后的用户信息 包括权限
            return R.ok(userRes);
        }else{

            return R.fail(400 , "用户名或密码错误");
        }

    }


    @PostMapping("/out")
    public R logout(HttpSession session){

        session.removeAttribute(SESSION_USER);

        return R.ok(null);
    }

}
